package com.tensquare.friend.interceptor;


import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //1. 得到请求头
        String header = request.getHeader("Authorization");
        System.out.println("header:" + header);
        //2. 判断是否有值
        if (StringUtils.isNotBlank(header) && header.startsWith("bearer")){
            //3.得到token
            String token = header.substring(7);
            System.out.println("token" + token);
            //4.解析token
            Claims claims = jwtUtil.parseJWT(token);
            System.out.println("interceptor  claims:" + claims);
            //5.放入作用域
            request.setAttribute("claims",claims);
        }
        return true;
    }
}
